<?php

namespace app\command;

use Kreait\Firebase\Factory;
use support\Log;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Output\OutputInterface;
use think\facade\Db;

#[AsCommand('check:topic', 'check topic')]
class CheckTopic extends Command
{
    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if (method_exists(\app\Env::class, 'load')) {
            $loadfile=file_exists(__DIR__.DIRECTORY_SEPARATOR.'dev.env')?'dev.env':'.env';
            \app\Env::load($loadfile);
        }

        $name = $input->getArgument('name');
        $output->writeln('Hello check:topic');

        $db = \support\Db::connection('mysql');
        $userTopicModel = new \app\common\model\UserTopic();

        $userTopics = $userTopicModel->connect('mysql')->cursor();

        $factory = (new Factory())->withServiceAccount(base_path().'/calm-segment-416609-56b780217794.json');
        $messaging = $factory->createMessaging();

        foreach ($userTopics as $userTopic) {
            $arr = [];
            try {
                $appInstance = $messaging->getAppInstance($userTopic->fcm_token);
                $subscriptions = $appInstance->topicSubscriptions();
                $arr = [];
                foreach ($subscriptions as $subscription) {
                    $arr[] = $subscription->topic();
                }
            } catch (\Exception $e) {
                Log::error('查询订阅主题失败-error:'.$e->getMessage().$e->getFile().$e->getLine());
            }
            if (empty($arr)) {
                $userTopicModel->connect('mysql')->where('id',$userTopic->id)->delete();
            }
        }

        return self::SUCCESS;
    }

}
